package com.zhu.qiniu;





import com.zhu.commons.utils.QIniuUtils;
import com.zhu.commons.utils.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/oss/file")
@Api(tags = "图片上传模块")
@CrossOrigin
@Slf4j
public class UploadController {


    private String url="re67i88y2.hd-bkt.clouddn.com";


    @PostMapping("/upload")
    @ApiOperation(value = "/upload")
    public R upload(@RequestParam("file") MultipartFile file){
        QIniuUtils qIniuUtils=new QIniuUtils();
        String originalFilename = file.getOriginalFilename(); //原始文件名称
        String filename=UUID.randomUUID().toString()+"."+ StringUtils.substringAfter(originalFilename,".");//文件名称、
        Boolean upload = qIniuUtils.upload(file, filename);
        String uploadUrl="http://"+url+"/"+filename;
        if(upload){
            return R.ok().data("url",uploadUrl);
        }
         return R.error().message("文件上传失败！");
    }

    @ApiOperation("测试Feign")
    @GetMapping("test")
    public R test(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("服务被调用了");
        return R.ok();
    }

    @DeleteMapping("/deleteByUrl/{url}")
    @ApiOperation(value = "/deleteByUrl")
    public R deleteFile(@PathVariable("url") String url){
        QIniuUtils qIniuUtils=new QIniuUtils();
        log.info("调用了接口删除图片 url:{}======================",url);
       if(qIniuUtils.deleteFile(url)){
           return R.ok();
       }
       return R.error().message("文件删除失败");
    }

}
